

import React, { useCallback, useEffect, useState } from 'react'
import { Form, Input, Button, Checkbox, message } from 'antd';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { fetchUserFromStorage, setUserStorage } from '../../utils/storage';
import { useDispatch, useSelector } from 'react-redux';
import {useNavigate} from "react-router";


import "./OpenLive.scss";
import { httpCloseLive, httpIsOpen, httpIsOpenLive, httpopenLive } from '../../apis';
import { SET_USER } from '../../store/action_type';
import { setUser } from '../../store/action';


const useIsOpenLive = () => {
  let [isOpenLive,setIsOpenLive] = useState(false);
  const user = useSelector(state=>state.user);
  const dispatcher = useDispatch();
  useEffect(()=>{
    // 查询用户是否开启直播间
    if(user.liveId) {
      setIsOpenLive(true);
      return ;
    } else {
      (async ()=>{
        let data = {
          userId: user.userId
        };
        let res = await httpIsOpenLive(data);
        if(res!==0) {
          dispatcher(setUser({
            ...user,
            liveId: res
          }));
        }
        if(res)setIsOpenLive(true);
        return ;
      })();
    }
    if(!user.liveId)setIsOpenLive(false);
  },[user,dispatcher]);
  return isOpenLive;
}


export default function OpenLive() {
  const navigate = useNavigate();
  const user = useSelector(state=>state.user);
  const dispatcher = useDispatch();

  // 用户是否已经开启了直播间
  let isOpenLive = useIsOpenLive();

  const gotoLiveRoom = ()=>{
    navigate(`/live/${user.liveId}`);
  }

  const onFinish = async (values: any) => {
    // 开启直播
    let data = {
      ...values,
      userId: user.userId
    };
    let res = await httpopenLive(data);

    // 这段代码加在这里会有问题
    // 这里的action会导致后面的useIsOpenLive里面的effect调用--但是那个时候组件已经被销毁。
    // dispatcher(setUser({
    //   ...user,
    //   liveId: res.data
    // }));
    // 跳转到直播间
    if(res) {
      console.log("开启直播:",res)
      navigate(`/live/${res}`);
    }
  };

  const closeLive = useCallback(async ()=>{
    let data = {};
    data.userId = user.userId;
    let res = httpCloseLive(data);
    if(res) {
      dispatcher(setUser({
        ...user,
        liveId: null
      }));
    }
  },[user]);


  

  return (
    <div className='OpenLive-container'>
      {
        !isOpenLive ? <>
          <Form
            name="basic"
            labelCol={{ span: 10 }}
            wrapperCol={{ span: 30 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item
              label="直播间标题"
              name="name"
              rules={[{ required: true, message: '请输入你的直播间标题' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="直播描述"
              name="description"
            >
              <Input />
            </Form.Item>


            <Form.Item
              label="封面图"
              name="backgroundURL"
            >
              <Input.Password />
            </Form.Item>

            <Form.Item
              label="直播间密码(可选)"
              name="password"
            >
              <Input.Password />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                开启直播
              </Button>
            </Form.Item>
          </Form>
        </>:
        <div className='ok-container'>
          <h2>已经开启直播间</h2>
          <Button type='primary' onClick={gotoLiveRoom}>前往直播间</Button>
          &nbsp;
          <Button type='primary' onClick={closeLive}>关闭直播间</Button>
        </div>
      }

    </div>
  )
}
